package com.xhd.servlet;

import java.io.File;
import java.io.IOException;
import java.net.URLDecoder;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.RequestContext;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.FileItem;

import com.xhd.Dao.SalerDao;
import com.xhd.Dao.SalerDaoImpl;
import com.xhd.vo.Fruits;
import com.xhd.vo.Order;

@WebServlet("/SalerServlet")
public class SalerServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;


    public SalerServlet() {
        super();
        // TODO Auto-generated constructor stub
    }


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//System.out.println("aaa");
				//解决中文乱码
				response.setContentType("text/html;charset=utf-8");
				//请求解决乱码
				request.setCharacterEncoding("utf-8");
				//响应解决乱码
				response.setCharacterEncoding("utf-8");
				
				String method = request.getParameter("method");
				if(method.equals("loginCheck")) {
					try {
						loginCheck(request,response);
					} catch (ServletException | IOException | SQLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				if(method.equals("changePwd")) {
					try {
						changePwd(request,response);
					} catch (ServletException | IOException | SQLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				if(method.equals("addFruit")) {
					try {
						addFruit(request,response);
					} catch (ServletException | IOException | SQLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				if(method.equals("addOrder")) {
					try {
						addOrder(request,response);
					} catch (ServletException | IOException | SQLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				if(method.equals("serchFruit")) {
					try {
						serchFruit(request,response);
					} catch (ServletException | IOException | SQLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				if(method.equals("serchPrice")) {
					try {
						serchPrice(request,response);
					} catch (ServletException | IOException | SQLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				if(method.equals("serchFruitinSaler")) {
					try {
						serchFruitinSaler(request,response);
					} catch (ServletException | IOException | SQLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
	}


	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(request, response);
	}
	
	protected void loginCheck(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException {
		String pwd = request.getParameter("pwd");
		SalerDao sd = new SalerDaoImpl();
		
		boolean flag = sd.loginCheck(pwd);
		if(flag) {
			HttpSession session=request.getSession();
			session.setAttribute("user", "1");
			request.setAttribute("err", "chenggong!!");
			request.getRequestDispatcher("SalerMenu.jsp").forward(request, response);
	
		}
		else {
			response.sendRedirect("Salerloginfail.jsp");
		}
			
	}
	
	
	protected void changePwd(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException {
		String pwd1 = request.getParameter("pwd1");//ԭ����
		String pwd2 = request.getParameter("pwd2");//������
		String pwd3 = request.getParameter("pwd3");//ȷ��������
		String error;
		SalerDao sd = new SalerDaoImpl();
		boolean flag = sd.loginCheck(pwd1);
		HttpSession session = request.getSession();
		
		if(flag){
			if(pwd2.equals(pwd3)){
				sd.updatePwd(pwd2);
				response.sendRedirect("changePwdsuccess.jsp");
			}
			else {
				
				error="error2";//�����������벻һ��
				session.setAttribute("error",error);
				request.getRequestDispatcher("changePwdfail.jsp").forward(request,response);
			}
		}
		else {
		
			error="error1";//ԭ�������
			session.setAttribute("error",error);
			request.getRequestDispatcher("changePwdfail.jsp").forward(request,response);
		}
	}
	
	protected void addFruit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException {

//		request.setCharacterEncoding("UTF-8");
//
//		String name=request.getParameter("fruit_name");
//		System.out.println(name);
//		String describe=request.getParameter("fruit_describe");
//		String picture=request.getParameter("fruit_picture");
//		String price=request.getParameter("fruit_price");
//		Fruits fruit=new Fruits(name,describe,picture,price);
//		SalerDao sd = new SalerDaoImpl();
//		try {
//			sd.addFruit(fruit);
//			response.sendRedirect("FruitAddSuccess.jsp");
//		} catch (SQLException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
		//原代码为上面的

		//设置编码
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        //上传到服务器的存放路径

		File file =new File(request.getSession().getServletContext().getRealPath("upload/"));    
		//如果文件夹不存在则创建    
		if  (!file .exists()  && !file .isDirectory())      
		{       
		    System.out.println("//原工作区下不存在upload文件夹，xc帮你创建");  
		    file .mkdir();    
		} else   
		{  
		    System.out.println("//已有upload文件夹存在，作为服务器端存取");  
		}
        String uploadFilePath = request.getSession().getServletContext().getRealPath("upload/");

        //判断上传的数据是不是多段数据
        if (isMultipart) {
            //创建工厂实现类
            DiskFileItemFactory factory = new DiskFileItemFactory();
            //创建临时文件目录
            File tempPath = new File("D:\\image");
            //设置临时文件存放的路径
            factory.setRepository(tempPath);
            //设置缓冲区大小
            factory.setSizeThreshold(10240);
            //用于解析上传数据的工具类ServletFileUpload
            ServletFileUpload upload = new ServletFileUpload(factory);
            //设置单个文件最大值
            upload.setSizeMax(61440000);

            //初始化为空
            String fruit_name = null;
            String fruit_describe = null;
            String fruit_picture = null;
            String fruit_price = null;
            String fruit_stock= null;
            String filename=null;
            List  mutify_picture=new ArrayList();
     
            //调用解析方法
            try {
                //定义一个集合 接受上传的所有请求参数
                List<FileItem> list = upload.parseRequest(request);
                //循环判断，每一个表单项，是普通类型，还是上传的文件
                for (FileItem fileItem : list) {
                    if (fileItem.isFormField()) {
                        //普通表单项
                        String filedName = fileItem.getFieldName();
                     
                        if (filedName.equals("fruit_name")) {
                        	fruit_name = fileItem.getString("UTF-8");
                        } else if (filedName.equals("fruit_describe")) {
                        	fruit_describe = fileItem.getString("UTF-8");
                        } else if (filedName.equals("fruit_price")) {
                        	fruit_price = fileItem.getString("UTF-8");
                        } else if (filedName.equals("fruit_stock")) {
                        	fruit_stock = fileItem.getString("UTF-8");
                        }

                    } else {
                        //上传的图片，获取到文件名
                        filename = fileItem.getName();
                        
                        if (filename!= null && !filename.equals("")) {
                            String str = filename.substring(filename.lastIndexOf(".") + 1);
                            //判断图片类型
                            if ("png".equals(str) || "jpg".equals(str) || "webp".equals(str)) {
                                //保存到服务器
                            	mutify_picture.add(filename);
                                File saveFile = new File(uploadFilePath, filename);
                                fileItem.write(saveFile);
                                
                                System.out.println("图片上传成功");
                            } else {
                                return;
                            }

                        }

                    }
                }
            } catch (Exception e) {

                e.printStackTrace();
            }

            //拿到LoginServlet中保存到session中的已经登录的user
           
            //创建对象
            fruit_picture=String.join("@", mutify_picture);
            Fruits fruit = new Fruits(fruit_name,fruit_describe,fruit_picture,fruit_price,"待售",fruit_stock);
            // 调用 方法处理业务
            SalerDao sd = new SalerDaoImpl();
            sd.addFruit(fruit);
            request.getRequestDispatcher("FruitAddSuccess.jsp").forward(request,response);
            }

     
		
	}
	
	protected void addOrder(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException {

		request.setCharacterEncoding("UTF-8");
		String stock=request.getParameter("stock");
		String price=request.getParameter("price");
		String order_buyer=request.getParameter("order_buyer");
		//System.out.println(order_buyer);
		String order_phone=request.getParameter("order_phone");
		//System.out.println(order_phone);
		String order_address=request.getParameter("order_address");
		String order_fruit=request.getParameter("order_fruit");
		String order_sum=request.getParameter("order_sum");
		String order_state="待处理";
		int sumNumber=Integer.parseInt(order_sum);
		int stockNumber=Integer.parseInt(stock);
		if (sumNumber-stockNumber>0) {
			response.sendRedirect("OrderAddFail.jsp");
		}else {
		Order order=new Order(order_buyer,order_phone,order_address,order_fruit,order_state,order_sum);
		SalerDao sd = new SalerDaoImpl();
		try {
			sd.addOrder(order);
			request.setAttribute("price", price);
			request.getRequestDispatcher("index.jsp").forward(request,response);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		}
	}
	
	protected void serchFruit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException {

		request.setCharacterEncoding("UTF-8");

		String serchfruit=request.getParameter("serchfruit");
		if(serchfruit==null||serchfruit=="") {
			response.sendRedirect("CheckFruits.jsp");
		}else {
			//System.out.println("name:"+serchfruit);
			SalerDao sd = new SalerDaoImpl();
			try {
				List<Fruits> serchlist=sd.serchFruit(serchfruit);
				request.setAttribute("serchlist", serchlist);
				request.getRequestDispatcher("CheckFruits.jsp").forward(request,response);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	protected void serchPrice(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException {

		request.setCharacterEncoding("UTF-8");

		String price1=request.getParameter("price1");
		String price2=request.getParameter("price2");
	
		if(price1==null||price1==""||price2==null||price2=="") {
			String p1 = "0";
			String p2 = "9999999";
			request.setAttribute("price1", p1);
			request.setAttribute("price2", p2);
			request.getRequestDispatcher("CheckFruits.jsp").forward(request,response);
		}
		request.setAttribute("price1", price1);
		request.setAttribute("price2", price2);
		request.getRequestDispatcher("CheckFruits.jsp").forward(request,response);
	}
	protected void serchFruitinSaler(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException {

		request.setCharacterEncoding("UTF-8");

		String serchfruit=request.getParameter("serchfruitinsaler");
		if(serchfruit==null||serchfruit=="") {
			response.sendRedirect("HistoryMessage.jsp");
		}else {
			//System.out.println("name:"+serchfruit);
			SalerDao sd = new SalerDaoImpl();
			try {
				List<Fruits> serchlistinsaler=sd.serchFruit(serchfruit);
				request.setAttribute("serchlistinsaler", serchlistinsaler);
				request.getRequestDispatcher("HistoryMessage.jsp").forward(request,response);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
